package platform.user.auth.token;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * 认证过滤器
 *
 * @author roamer
 * @version V1.0
 * @date 2019-03-10 15:56
 */
public class TokenAuthenticationFilter extends GenericFilterBean {

    @Autowired
    private TokenAuthenticator tokenAuthenticator;


    @Override
    public void doFilter(
            ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException,
                                                                                              ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        String tokenValue = req.getHeader("token");
        if (tokenValue == null && req.getCookies() != null) {
            for (Cookie cookie : req.getCookies()) {
                if ("token".equals(cookie.getName())) {
                    tokenValue = cookie.getValue();
                }
            }

        }

        tokenAuthenticator.authenticateToken(tokenValue, "");
        filterChain.doFilter(request, response);
    }
}
